/* eslint-disable */
import { cloneDeep, isString, isArray, isNumber } from 'lodash'
import {
  GridItemDataInterface,
  KeyValueStore,
} from '@/components/interface/grid-item-data-interface'
import { getWidgetJson } from '@/config/setting-chart'
import {
  ChartDetailsEnum,
  CONFIGURATION_NAME,
  GRAPH_ARRAY,
  filterFormTypeName,
  ChartDataTypeEnum,
} from '@/config/contant'
import moment from 'moment'
import Big from 'big.js'

/**
 * 绑定数据
 * @param gridItem
 * @param dataResult
 */
export function bindChartData(
  gridItem: GridItemDataInterface | null,
  dataResult: KeyValueStore
): GridItemDataInterface | null {
  if (gridItem) {
    if (isString(gridItem.chartType) && /\|/.test(gridItem.chartType)) {
      gridItem.chartType = gridItem.chartType.split('|')
    }
  }
  const result = cloneDeep(gridItem)
  if (result) {
    // if (result?.chartType[1] === 'geographicMap') {
    //   return bindGeoMapData(result, dataResult)
    // }
    let xAxisAttribute: Array<string | number> = []
    // const yAxisAttribute:Array<string|number> = []
    // const aggrTypeAttribute: Array<string | number> = []
    result.dataQuery = dataResult.query
    const { widgetJson } = dataResult.query.data
    if (!result.chartOptions) {
      result.chartOptions = {}
    }
    result.chartOptions.value = [] as Array<any>

    if (dataResult.data.length > 20000) {
      result.showChart = false
      result.statusText = '数据量超限'
    } else {
      const { keys, values, groups = [] } = widgetJson.config
      xAxisAttribute = keys
        .concat(groups)
        .map((item: { col: string }) => item.col)
      result.chartOptions = {
        ...result.chartOptions,
        ...dataResult.formData,
      }
      delete result.chartOptions.type // type字段不用于渲染还可能会影响render
      result.chartOptions.value = dataResult.data

      // result.chartOptions.labelKey = dataResult.formData.labelKey
      // const valueKeys = dataResult.formData.valueKey.reduce(
      //   (rec: Array<string>, item: KeyValueStore) => {
      //     const rec_ = item.value !== '' ? [...rec, item.value] : rec
      //     return rec_
      //   },
      //   []
      // )

      // result.chartOptions.valueKey = valueKeys[0] || 'valueKey'

      const valueKeys = (values as Array<{ col: string }>).map((v) => v.col)

      if (
        [undefined, ''].includes(result.chartOptions.xAxisAttribute) &&
        result.chartOptions.labelKey
      ) {
        result.chartOptions.xAxisAttribute = result.chartOptions.labelKey
      }
      let chartTypeUsed: any = result.chartType

      if (isArray(result.chartType)) {
        ;[, chartTypeUsed] = result.chartType
      } else if (/\|/.test(result.chartType)) {
        ;[, chartTypeUsed] = result.chartType.split('|')
      }

      if (groups.length > 0) {
        // renderOption.seriesField = groups[0].col
        result.chartOptions.colorField = groups[0].col
      } else if (
        groups.length === 0 &&
        ['scatterplot', 'wordCloud'].includes(chartTypeUsed)
      ) {
        // 选中分组字段(scatterplot)或词色(wordCloud)后，清空已选择的内容
        result.chartOptions.colorField = undefined
      }

      if (chartTypeUsed !== 'scatterplot') {
        result.chartOptions.xAxisAttribute = result.chartOptions.labelKey // (aggrTypeAttribute && aggrTypeAttribute.length > 0  && !checkIsNumber(dataResult, aggrTypeAttribute))?  aggrTypeAttribute[0] : ( xAxisAttribute && xAxisAttribute.length > 0 ? xAxisAttribute[0] : '')
      }
      result.chartOptions.yAxisAttribute =
        valueKeys.length > 1 ? valueKeys : valueKeys[0] //  aggrTypeAttribute && aggrTypeAttribute.length > 0  && checkIsNumber(dataResult, aggrTypeAttribute)? aggrTypeAttribute[0] :  (yAxisAttribute && yAxisAttribute.length > 0 ?  yAxisAttribute[0] : '')
      // result.formData = dataResult.formData
      result.columns = dataResult.columns

      if (
        isArray(result.chartOptions.valueKey) &&
        [
          // `${ChartDetailsEnum.scatterplot}`,
          `${ChartDetailsEnum.groupBarChart}`,
          `${ChartDetailsEnum.areaChart}`,
          `${ChartDetailsEnum.lineChart}`,
          `${ChartDetailsEnum.stackBarChart}`,
        ].includes(chartTypeUsed)
      ) {
        result.chartOptions.yAxisAttribute = valueKeys
      }
      if (chartTypeUsed === `${ChartDetailsEnum.heatmapMatrix}`) {
        if (
          Array.isArray(result.chartOptions.colors) &&
          (result.chartOptions.colors as Array<string>)[0]
        ) {
          const color = (result.chartOptions.colors as Array<string>)[0]
          result.chartOptions.legendBasicColor = color
        }

        result.chartOptions.labelKeyY = keys[1].col
        result.chartOptions.valueKey = keys[1].col
        result.chartOptions.yAxisAttribute = keys[1].col
        result.chartOptions.heatMapDataKey = values[0].col

        result.chartOptions.axisCategoricalDataSelection = 'all'
        result.chartOptions.value.forEach(
          (dataItem: KeyValueStore, index: number) => {
            result.chartOptions.value[index][
              result.chartOptions.yAxisAttribute
            ] = `${
              result.chartOptions.value[index][
                result.chartOptions.yAxisAttribute
              ]
            }`
          }
        )
        // }
      }
      // if (chartTypeUsed === ChartDetailsEnum.bubbleScatterChart) { // 目前的气泡图是统一气泡大小，不需要指定sizeField
      //   result.chartOptions.valueKey = keys[1].col
      //   result.chartOptions.sizeField = values[0].col
      // }
      // 柱线混合的特殊属性
      if (
        isArray(valueKeys) &&
        valueKeys.length > 0 &&
        chartTypeUsed === `${ChartDetailsEnum.dualAxesChart}`
      ) {
        result.chartOptions.value = [
          result.chartOptions.value,
          result.chartOptions.value,
        ]
        if (valueKeys.length > 1) {
          result.chartOptions.yAxisAttribute = [
            valueKeys[0],
            valueKeys.slice(1),
          ]
          result.chartOptions.valueKey = valueKeys
        } else {
          // 只有1个度量时
          result.chartOptions.yAxisAttribute = [valueKeys[0], [valueKeys[0]]]
          result.chartOptions.valueKey = [valueKeys[0], valueKeys[0]]
        }
      }
      // 解决组件库labelKey不支持数字类型的问题
      if (
        [
          `${ChartDetailsEnum.pieChart}`,
          `${ChartDetailsEnum.donutChart}`,
        ].includes(chartTypeUsed)
      ) {
        result.chartOptions.value.forEach((dataItem: any) => {
          dataItem[result.chartOptions.labelKey] = isNumber(
            dataItem[result.chartOptions.labelKey]
          )
            ? `${dataItem[result.chartOptions.labelKey]}`
            : dataItem[result.chartOptions.labelKey]
        })
      }
      // areaRangeChart BoxLineChart
      if ([`${ChartDetailsEnum.areaRangeChart}`].includes(chartTypeUsed)) {
        const { confidence } = widgetJson.config
        const lowerKey = confidence.lower.value
        const upperKey = confidence.upper.value
        result.chartOptions.value = result.chartOptions.value.map(
          (dataItem: any) => {
            return {
              ...dataItem,
              range: [dataItem[lowerKey], dataItem[upperKey]],
            }
          }
        )
        result.chartOptions.valueKey = 'range'
        result.chartOptions.yAxisAttribute =
          result.chartOptions.yAxisAttribute.slice(0, -2)
      }

      result.showChart = true
    }
  }
  /**
   * 清空null key 的情况
   */
  result &&
    result.chartOptions.value.forEach((dataItem: KeyValueStore) => {
      Object.keys(dataItem).forEach((key) => {
        if (/^\[object/.test(key)) {
          delete dataItem[key]
        }
      })
    })
  if (
    result &&
    isString(result.chartOptions.xAxisAttribute) &&
    result.chartOptions.labelKeyFormat // Todo labelKeyFormat???????
  ) {
    result.chartOptions.value.forEach((valueItem: any) => {
      if (valueItem[result.chartOptions.xAxisAttribute]) {
        valueItem[result.chartOptions.xAxisAttribute] = moment(
          valueItem[result.chartOptions.xAxisAttribute]
        ).format(result.chartOptions.labelKeyFormat)
      }
    })
  }

  // if ( // 应该是走 chart的visibleItemsNumber
  //   result &&
  //   ['pieChart', 'donutChart'].includes(result.chartType[1]) &&
  //   result.formData &&
  //   result.formData.showNumber > 0 &&
  //   isArray(result.chartOptions.value)
  // ) {
  //   let newValue: Array<any> = result.chartOptions.value
  //   if (result.chartOptions.value.length > result.formData.showNumber) {
  //     newValue = result.chartOptions.value.slice(0, result.formData.showNumber)
  //     for (
  //       let i = result.formData.showNumber;
  //       i < result.chartOptions.value.length;
  //       i++
  //     ) {
  //       newValue[result.formData.showNumber - 1][
  //         result.chartOptions.valueKey
  //       ] += result.chartOptions.value[i][result.chartOptions.valueKey]
  //     }
  //     newValue[result.formData.showNumber - 1][result.chartOptions.labelKey] =
  //       '其他'
  //     result.chartOptions.value = newValue
  //   }
  //   result.chartOptions.visibleItemsNumber = newValue.length + 1 // 这里外部处理了，chart内部逻辑就先屏蔽掉
  //   result.chartOptions.labelTextMaxlength = 10
  //   // result.chartOptions.labelIsShow = false
  // }

  if (
    result &&
    ['barChart', 'groupBarChart', 'stackBarChart'].includes(
      result.chartType[1]
    ) &&
    result.chartOptions.axisCategoricalDataSelection === 'yAxis'
  ) {
    const xAttribute =
      typeof result.chartOptions.xAxisAttribute === 'string'
        ? [result.chartOptions.xAxisAttribute]
        : result.chartOptions.xAxisAttribute
    const yAttribute =
      typeof result.chartOptions.yAxisAttribute === 'string'
        ? [result.chartOptions.yAxisAttribute]
        : result.chartOptions.yAxisAttribute
    result.chartOptions.xAxisAttribute = yAttribute
    result.chartOptions.yAxisAttribute = xAttribute
  }
  return result
}

/**
 * 保存参数
 */
export function buildSaveParameters(
  gridItem: GridItemDataInterface,
  deleteId?: boolean
): KeyValueStore {
  if (checkIsFilterForm(gridItem)) {
    return buildFilterFormParams(gridItem, deleteId)
  }
  const query = gridItem.dataQuery ? gridItem.dataQuery : {}
  parseDiffBarConfig(gridItem)
  let chartConfig = JSON.parse(
    JSON.stringify({
      ...gridItem.chartOptions,
      ...handleInteractionActionObject(gridItem.chartOptions),
    })
  )
  if (!chartConfig.titleHeight) {
    const defaultConfig = {}
    chartConfig = { ...chartConfig, ...defaultConfig }
  }
  if (
    gridItem.chartType !== CONFIGURATION_NAME &&
    gridItem.chartType !== 'text'
  ) {
    chartConfig.value = []
  }
  if (gridItem.chartOptions.subChartOptions) {
    chartConfig.subChartOptions.value = []
  }
  // geomap 清空geolayer内部数据
  if (gridItem.chartType[1] === 'geographicMap') {
    if (chartConfig.geoLayer && chartConfig.geoLayer.length > 0) {
      chartConfig.geoLayer.forEach((layer: any, index: number) => {
        chartConfig.geoLayer[index].config.value = []
      })
    }
  }
  const result = {
    data: {
      projectId: localStorage.getItem('projectId'),
      // 'id': gridItem.widgetId,
      // 'randomId': Math.floor(Math.random()* 10000),
      // vistabs组件的标题用的是mainTitle字段
      name:
        gridItem.chartOptions.title || gridItem.chartOptions.mainTitle
          ? gridItem.chartOptions.title || gridItem.chartOptions.mainTitle
          : Array.isArray(gridItem.chartType)
          ? gridItem.chartType[0]
          : gridItem.chartType,
      tid: gridItem.chartOptions.dataId,
      type: getWidgetType(gridItem),
      data: {
        // formData: gridItem.formData,
        widgetJson: query.data
          ? query.data.widgetJson
          : getWidgetJson(gridItem.chartOptions),
        chartType: gridItem.chartType,
        x: gridItem.x,
        y: gridItem.y,
        w: gridItem.w,
        h: gridItem.h,
        i: gridItem.i,
        chartOptions: chartConfig,
        widgetType: gridItem.widgetType,
        interactionJson: gridItem?.interactionJson || {},
        numberFormat: gridItem?.numberFormat,
        interactActive: gridItem?.interactActive ?? undefined,
      },
    },
  }
  if (!deleteId) {
    ;(result.data as any).id = gridItem.widgetId
  }
  if (GRAPH_ARRAY.includes(gridItem.chartType[1])) {
    // graph 数据集没有对应的id，统一删除掉
    delete result.data.tid
  }
  return result
}

/** 检测是否是筛选器组件 */
export const checkIsFilterForm = (gridItem: GridItemDataInterface) => {
  return Array.isArray(gridItem.chartType)
    ? gridItem.chartType.includes(filterFormTypeName)
    : gridItem.chartType === filterFormTypeName
}

/** 筛选器控件保存参数生成 */
const buildFilterFormParams = (
  gridItem: GridItemDataInterface,
  deleteId?: boolean
) => {
  const result: any = {
    data: {
      projectId: localStorage.getItem('projectId'),
      name: gridItem.chartOptions.title
        ? gridItem.chartOptions.title
        : Array.isArray(gridItem.chartType)
        ? gridItem.chartType[0]
        : gridItem.chartType,
      tid: gridItem.chartOptions.dataId,
      type: getWidgetType(gridItem),
      data: {
        widgetJson: {},
        chartType: gridItem.chartType,
        x: gridItem.x,
        y: gridItem.y,
        w: gridItem.w,
        h: gridItem.h,
        i: gridItem.i,
        chartOptions: JSON.parse(JSON.stringify(gridItem.chartOptions)),
        widgetType: gridItem.widgetType,
        interactionJson: gridItem?.interactionJson || {},
      },
    },
  }

  if (!deleteId) {
    ;(result.data as any).id = gridItem.widgetId
  }
  return result
}

/**
 * 差异BarChart是单独的一种类型
 * @param chartConfig chart 配置
 */
function parseDiffBarConfig(gridItem: GridItemDataInterface) {
  const {
    chartType,
    chartOptions: { diffBar },
  } = gridItem
  if (chartType[1] !== 'barChart') {
    return
  }
  gridItem.chartOptions.realChartType =
    diffBar === true ? 'diffBarChart' : 'barChart'
}

/**
 * 兼容老图表interactions属性，赋值为undefined
 */
export function handleInteractionActionObject(chartOptions: any) {
  const { interactions } = chartOptions
  if (interactions) {
    return {
      interactions: undefined,
    }
  }
  return {}
}

const getWidgetType = (gridItem: GridItemDataInterface) => {
  return gridItem.chartType === 'text'
    ? 'text'
    : gridItemIsMyComponent(gridItem)
    ? 'task_copy'
    : gridItemIsRecommend(gridItem)
    ? 'recommend'
    : checkIsFilterForm(gridItem)
    ? 'filterForm'
    : 'dataset'
}

/**
 * 判断是否为我的组件
 * @param gridItem
 */
export function gridItemIsMyComponent(
  gridItem: GridItemDataInterface
): boolean {
  return (
    gridItem &&
    gridItem.formData &&
    (gridItem.formData.dataType === ChartDataTypeEnum.myComponent ||
      gridItem.formData.dataType === 'task')
  )
}

export function gridItemIsRecommend(gridItem: GridItemDataInterface): boolean {
  return (
    gridItem &&
    gridItem.formData &&
    gridItem.formData.dataType === ChartDataTypeEnum.recommend
  )
}

export function parseGraphEdgeWeight(gridItem: GridItemDataInterface) {
  const { value } = gridItem.chartOptions
  let minWeight = Number.MAX_SAFE_INTEGER
  let maxWeight = Number.MIN_SAFE_INTEGER
  if (value.edges && value.edges.length > 0) {
    value.edges.forEach((edge: KeyValueStore) => {
      minWeight = Math.min(minWeight, edge.weight)
      maxWeight = Math.max(maxWeight, edge.weight)
    })
  } else {
    minWeight = 0
    maxWeight = 0
  }
  gridItem.chartOptions.edgeWeightRange = [
    +minWeight.toFixed(3),
    +maxWeight.toFixed(3),
  ]
}

/** 数字格式化 */
export function getFormatValue(value: any, type: string, digit: number) {
  if (typeof value === 'number') {
    if (type === '%') {
      // 百分比计数法
      value = `${Big(value).times(100).toFixed(digit)}%`
    } else if (type === 'E-NOTATION') {
      // 科学计数法
      value = `${Big(value).toExponential(digit)}`
    }
  }
  return value
}
